import copy
import os
import time
from typing import List, Dict, Any, Optional, Tuple
from PyQt6.QtCore import QThread, pyqtSignal, QMutex

import Global
from 数据库.DbManager import DbManager

class UserManager:
    """
    用户管理类，基于DbManager进行数据库操作
    """
    # 用户状态常量
    STATUS_UNUSED = 0  # 待用账号
    STATUS_RUNNING = 1  # 运行账号
    STATUS_SUCCESS = 2  # 成功账号
    STATUS_FAILED = 3   # 失败账号
    STATUS_UPLOAD = 4   # 上传账号
    
    _used_users = []    # 已使用的用户列表，避免重复使用
    _used_emails = []   # 已使用的邮箱列表，避免重复使用
    _data_mutex = QMutex()  # 数据访问互斥锁
    _email_mutex = QMutex()  # 邮箱访问专用互斥锁
    _is_initialized = False  # 初始化标志
    _user_loader = None  # 用户数据加载器
    
    @staticmethod
    def initialize():
        """初始化用户管理模块"""
        if UserManager._is_initialized:
            return True
            
        # 初始化数据库
        if not DbManager.initialize():
            print("初始化数据库失败")
            return False
            
        # 异步加载用户数据
        UserManager._load_users_async()
        return True
    
    @staticmethod
    def _load_users_async():
        """异步加载用户数据"""
        class UserDataLoader(QThread):
            finished = pyqtSignal(bool)
            
            def __init__(self, parent=None):
                super().__init__(parent)
                
            def run(self):
                try:
                    # 这里不需要实际加载数据，只需确保数据库已初始化
                    # 实际数据会在需要时通过DbManager查询
                    success = DbManager.initialize()
                    if success and Global.mainWindow:
                        # 启用相关按钮
                        Global.mainWindow.pushButton_UseAccount.setEnabled(True)
                        Global.mainWindow.pushButton_FailAccount.setEnabled(True)
                        Global.mainWindow.pushButton_SuccessAccount.setEnabled(True)
                        Global.mainWindow.pushButton_RunAccount.setEnabled(True)
                        Global.mainWindow.pushButton_UploadAccount.setEnabled(True)
                        Global.mainWindow.pushButton_mailAccount.setEnabled(True)
                    
                    self.finished.emit(success)
                    UserManager._is_initialized = success
                except Exception as e:
                    print(f"加载用户数据异常: {str(e)}")
                    self.finished.emit(False)

        UserManager._user_loader = UserDataLoader()
        UserManager._user_loader.finished.connect(UserManager._on_user_data_loaded)
        UserManager._user_loader.start()
    
    @staticmethod
    def _on_user_data_loaded(success: bool):
        """用户数据加载完成后的回调"""
        if UserManager._user_loader:
            UserManager._user_loader.deleteLater()
            UserManager._user_loader = None
        
        if not success:
            print("用户数据加载失败")
    
    @staticmethod
    def get_users(status: int = None, count: int = -1, offset: int = 0, conditions: Dict[str, Any] = None, fields: List[str] = None, format: str = 'dict') -> List[Any]:
        """
        按状态获取用户列表，支持查询所有数据和自定义查询条件
        
        Args:
            status: 用户状态，None表示查询所有状态
            count: 获取数量，-1表示不限制数量
            offset: 偏移量
            conditions: 自定义查询条件，字典格式{字段名:值}
            fields: 自定义查询字段列表，默认查询所有主要字段
            format: 返回数据格式，'dict'返回字典列表，'list'返回二维列表，'sql_result'返回原始SQL结果
            
        Returns:
            如果format='dict'，返回List[Dict]字典列表
            如果format='list'，返回List[List]二维列表，其中第一列为累加序号
            如果format='sql_result'，返回(rows, fields)元组，包含原始SQLite查询结果和字段列表
        """
        conn = DbManager.get_conn()
        if not conn:
            return []
            
        try:
            cursor = conn.cursor()
            
            # 构建查询字段
            default_fields = ["id", "user", "pass", "user_id", "token", "mail", "mail_pass", "card_name", "source_info", "upload_id", "flag"]
            
            # 如果指定了查询字段，使用指定字段，否则使用默认字段
            select_fields = fields if fields else default_fields
            
            # 确保字段列表不为空
            if not select_fields:
                select_fields = default_fields

            # 处理update_time字段，转换为北京时间
            processed_select_fields = []
            for field in select_fields:
                if field == 'update_time':
                    processed_select_fields.append("datetime(update_time, '+8 hours') AS update_time")
                else:
                    processed_select_fields.append(field)

            # 构建查询SQL
            query = f"SELECT {', '.join(processed_select_fields)} FROM user_info"
            params = []
            
            # 构建查询条件
            where_clauses = []
            
            # 添加状态过滤条件
            if status is not None:
                where_clauses.append("flag = ?")
                params.append(status)
            
            # 添加自定义查询条件
            if conditions:
                for field, value in conditions.items():
                    if value is not None:
                        if isinstance(value, str) and '%' in value:
                            # 如果包含%，则使用LIKE查询
                            where_clauses.append(f"{field} LIKE ?")
                        else:
                            where_clauses.append(f"{field} = ?")
                        params.append(value)
            
            # 合并所有查询条件
            if where_clauses:
                query += " WHERE " + " AND ".join(where_clauses)
                
            # 添加排序
            query += " ORDER BY update_time desc"
            
            # 添加分页
            if count > 0:
                query += " LIMIT ?"
                params.append(count)
                
                if offset > 0:
                    query += " OFFSET ?"
                    params.append(offset)
            
            cursor.execute(query, params)
            
            # 如果要求直接返回SQL结果，则返回结果和字段
            if format == 'sql_result':
                rows = cursor.fetchall()
                return rows, select_fields
            
            rows = cursor.fetchall()

            if format == 'dict':
                # 返回字典列表
                result = [dict(row) for row in rows]
                return result
            elif format == 'list':

                # 返回二维列表，第一列为累加序号
                # 状态文本映射
                status_text = {
                    UserManager.STATUS_UNUSED: '待用',
                    UserManager.STATUS_RUNNING: '运行',
                    UserManager.STATUS_SUCCESS: '成功',
                    UserManager.STATUS_FAILED: '失败',
                    UserManager.STATUS_UPLOAD: '上传'
                }

                # 预先分配列表空间
                result = [[None] * len(select_fields) for _ in range(len(rows))]
                字段 = select_fields.copy()
                字段.remove('id')
                # 优化：减少重复字典转换
                for i, row in enumerate(rows):
                    row_dict = dict(row)
                    row_data = result[i]
                    
                    # 序号
                    row_data[0] = str(i + 1)
                    for index, field in enumerate(字段, start=1):
                        value = row_dict.get(field, '')
                        if field =='flag':
                            row_data[index] = status_text.get(value, '')
                        else:
                            row_data[index] = str(value or '')
                return result
            else:
                # 不支持的格式，返回空列表
                return []
        except Exception as e:
            Global.LOGE(f"查询用户数据失败: {e}")
            return []
        finally:
            DbManager.release_connection(conn)
            
    @staticmethod
    def count_users(status: int = None, conditions: Dict[str, Any] = None) -> int:
        """
        统计用户数量
        
        Args:
            status: 用户状态，None表示统计所有状态
            conditions: 自定义查询条件，字典格式{字段名:值}
            
        Returns:
            int: 用户数量
        """
        conn = DbManager.get_conn()
        if not conn:
            return 0
            
        try:
            cursor = conn.cursor()
            
            # 构建查询SQL
            query = "SELECT COUNT(*) as count FROM user_info"
            params = []
            
            # 构建查询条件
            where_clauses = []
            
            # 添加状态过滤条件
            if status is not None:
                where_clauses.append("flag = ?")
                params.append(status)
            
            # 添加自定义查询条件
            if conditions:
                for field, value in conditions.items():
                    if value is not None:
                        if isinstance(value, str) and '%' in value:
                            # 如果包含%，则使用LIKE查询
                            where_clauses.append(f"{field} LIKE ?")
                        else:
                            where_clauses.append(f"{field} = ?")
                        params.append(value)
            
            # 合并所有查询条件
            if where_clauses:
                query += " WHERE " + " AND ".join(where_clauses)
                
            # 执行查询
            cursor.execute(query, params)
            result = cursor.fetchone()
            return result['count'] if result else 0
        except Exception as e:
            print(f"统计用户数据失败: {e}")
            return 0
        finally:
            DbManager.release_connection(conn)
    
    @staticmethod
    def get_user_info(count: int) -> List[Dict]:
        """
        批量获取可用的用户账号数据
        
        Args:
            count: 需要获取的账号数量
            
        Returns:
            List[Dict]: 获取到的账号列表，如果不足则返回实际数量
        """
        UserManager._data_mutex.lock()
        try:
            # 先从运行账号中筛选未使用的
            conn = DbManager.get_conn()
            if not conn:
                return []
                
            try:
                cursor = conn.cursor()
                # 拼接SQL查询条件，排除已使用的用户
                placeholders = ','.join(['?'] * len(UserManager._used_users)) if UserManager._used_users else "''"
                query = f"""
                    SELECT * FROM user_info 
                    WHERE flag = {UserManager.STATUS_RUNNING} 
                    AND user NOT IN ({placeholders})
                    LIMIT ?
                """
                params = UserManager._used_users + [count] if UserManager._used_users else [count]
                cursor.execute(query, params)
                running_users = [dict(row) for row in cursor.fetchall()]
                
                # 如果运行账号不足，从待用账号中获取
                if len(running_users) < count:
                    remaining = count - len(running_users)
                    
                    # 获取待用账号
                    cursor.execute(
                        f"SELECT * FROM user_info WHERE flag = {UserManager.STATUS_UNUSED} LIMIT ?", 
                        (remaining,)
                    )
                    unused_users = [dict(row) for row in cursor.fetchall()]
                    
                    # 修改待用账号状态为运行中
                    write_conn = DbManager.get_conn(for_writing=True)
                    if write_conn and unused_users:
                        unused_ids = [user['id'] for user in unused_users]
                        placeholders = ','.join(['?'] * len(unused_ids))
                        write_cursor = write_conn.cursor()
                        write_cursor.execute(
                            f"UPDATE user_info SET flag = {UserManager.STATUS_RUNNING}, update_time = CURRENT_TIMESTAMP WHERE id IN ({placeholders})",
                            unused_ids
                        )
                        write_conn.commit()
                    
                    # 合并结果
                    running_users.extend(unused_users)
                
                # 记录已使用账号
                for user in running_users:
                    # 只有运行中的账号才添加到黑名单，成功/失败/上传账号不添加
                    if user['user'] not in UserManager._used_users and user.get('flag', 0) not in (UserManager.STATUS_SUCCESS, UserManager.STATUS_FAILED, UserManager.STATUS_UPLOAD):
                        UserManager._used_users.append(user['user'])


                
                return running_users
            finally:
                DbManager.release_connection(conn)
        except Exception as e:
            print(f"批量获取用户账号数据失败: {e}")
            return []
        finally:
            UserManager._data_mutex.unlock()
    
    @staticmethod
    def update_user_status(username: str, status: int, additional_data: dict = None) -> bool:
        """
        更新用户状态
        
        Args:
            username: 用户名
            status: 新状态
            additional_data: 其他需要更新的数据
            
        Returns:
            bool: 是否更新成功
        """
        try:
            # 先查询用户ID
            conn = DbManager.get_conn()
            if not conn:
                return False
                
            try:
                cursor = conn.cursor()
                cursor.execute("SELECT id FROM user_info WHERE user = ?", (username,))
                result = cursor.fetchone()
                if not result:
                    return False
                    
                user_id = result['id']
                
                # 从已使用列表中移除
                if username in UserManager._used_users:
                    UserManager._used_users.remove(username)

                
                # 准备更新数据
                data = additional_data or {}
                data['flag'] = status
                UserManager._data_mutex.lock()
                try:
                    update_result =DbManager.update_user_info(user_id, data)
                finally:
                    UserManager._data_mutex.unlock()
                # 更新用户状态
                return update_result
            finally:
                DbManager.release_connection(conn)
        except Exception as e:
            print(f"更新用户状态失败: {e}")
            return False
    
    @staticmethod
    def batch_update_user_status(usernames: List[str], status: int, additional_data: dict = None) -> List[bool]:
        """
        批量更新用户状态（事务优化版本，使用单个大事务提升性能）
        
        Args:
            usernames: 用户名列表
            status: 新状态
            additional_data: 其他需要更新的数据
            
        Returns:
            List[bool]: 每个用户的更新结果列表
        """
        # 参数验证
        if not usernames:
            return []
        
        if not isinstance(usernames, list):
            Global.LOGE(f"批量更新用户状态失败: usernames必须是列表类型，当前类型: {type(usernames)}")
            return [False] * len(usernames)
            
        if not isinstance(status, int):
            Global.LOGE(f"批量更新用户状态失败: status必须是整数类型，当前类型: {type(status)}")
            return [False] * len(usernames)
            
        if additional_data is not None and not isinstance(additional_data, dict):
            Global.LOGE(f"批量更新用户状态失败: additional_data必须是字典类型，当前类型: {type(additional_data)}")
            return [False] * len(usernames)
        
        total_usernames = len(usernames)
        results = []
        conn = None
        
        try:
            # 获取写数据库连接
            conn = DbManager.get_conn(for_writing=True)
            if not conn:
                Global.LOGE("获取数据库连接失败")
                return [False] * total_usernames
                
            cursor = conn.cursor()
            
            # 开始单个大事务
            conn.execute("BEGIN TRANSACTION")
            try:
                UserManager._data_mutex.lock()
                
                try:
                    # 分批查询用户ID（避免SQL IN子句参数过多）
                    QUERY_BATCH_SIZE = 500
                    all_user_data = {}
                    
                    for batch_start in range(0, total_usernames, QUERY_BATCH_SIZE):
                        batch_end = min(batch_start + QUERY_BATCH_SIZE, total_usernames)
                        batch_usernames = usernames[batch_start:batch_end]
                        
                        # 批量查询当前批次的用户ID
                        placeholders = ','.join(['?'] * len(batch_usernames))
                        query_sql = f"SELECT id, user FROM user_info WHERE user IN ({placeholders})"
                        cursor.execute(query_sql, batch_usernames)
                        batch_user_data = {row['user']: row['id'] for row in cursor.fetchall()}
                        all_user_data.update(batch_user_data)
                    
                    # 在同一事务中批量更新所有用户
                    for username in usernames:
                        if username in all_user_data:
                            user_id = all_user_data[username]
                            
                            try:
                                # 从已使用列表中移除
                                if username in UserManager._used_users:
                                    UserManager._used_users.remove(username)
                                
                                # 准备更新数据
                                data = additional_data.copy() if additional_data else {}
                                data['flag'] = status
                                
                                # 构建更新SQL
                                update_data = data.copy()
                                if 'update_time' in update_data:
                                    del update_data['update_time']
                                    
                                set_clause_parts = [f"{key} = ?" for key in update_data.keys()]
                                set_clause_parts.append("update_time = CURRENT_TIMESTAMP")
                                set_clause = ", ".join(set_clause_parts)
                                values = list(update_data.values())
                                values.append(user_id)
                                
                                update_sql = f"UPDATE user_info SET {set_clause} WHERE id = ?"
                                cursor.execute(update_sql, values)
                                
                                # 检查更新结果
                                if cursor.rowcount > 0:
                                    results.append(True)
                                else:
                                    Global.LOGE(f"用户 {username} 更新失败: 没有影响任何行")
                                    results.append(False)
                                    
                            except Exception as e:
                                Global.LOGE(f"更新用户 {username} 失败: {e}")
                                results.append(False)
                        else:
                            Global.LOGE(f"用户 {username} 不存在")
                            results.append(False)
                            
                finally:
                    UserManager._data_mutex.unlock()
                
                # 统一提交所有更新操作
                conn.commit()
                success_count = sum(results)
            except Exception as e:
                # 统一回滚所有操作
                conn.rollback()
                Global.LOGE(f"批量更新事务回滚: {e}")
                # 确保返回正确长度的结果列表
                if len(results) < total_usernames:
                    results.extend([False] * (total_usernames - len(results)))
                raise e
                
        except Exception as e:
            Global.LOGE(f"批量更新用户状态失败: {e}")
            # 确保返回正确长度的结果列表
            if len(results) < total_usernames:
                results.extend([False] * (total_usernames - len(results)))
                
        finally:
            if conn:
                DbManager.release_connection(conn)
                
        return results
    



    @staticmethod
    def insert_user(user_data: Dict) -> int:
        """
        插入单个用户数据
        
        Args:
            user_data: 用户数据字典，必须包含'user'字段
            
        Returns:
            int: 新插入记录的ID，失败返回0
        """
        if not user_data or 'user' not in user_data:
            print("插入用户数据失败：必须提供user字段")
            return 0
            
        # 确保有flag字段
        if 'flag' not in user_data:
            user_data['flag'] = UserManager.STATUS_UNUSED
            
        # 使用DbManager插入数据
        return DbManager.insert_user_info(user_data)
        
    @staticmethod
    def batch_insert_users(user_data_list: List[Dict]) -> int:
        """
        批量插入用户数据
        
        Args:
            user_data_list: 用户数据字典列表
            
        Returns:
            int: 成功插入的记录数
        """
        if not user_data_list:
            return 0
            
        success_count = 0
        conn = DbManager.get_conn(for_writing=True)
        if not conn:
            return 0
            
        try:
            cursor = conn.cursor()
            
            # 开始事务
            conn.execute("BEGIN TRANSACTION")
            
            for user_data in user_data_list:
                if not user_data or 'user' not in user_data:
                    continue
                    
                # 确保有flag字段
                if 'flag' not in user_data:
                    user_data['flag'] = UserManager.STATUS_UNUSED
                
                # 准备SQL语句，使用INSERT OR IGNORE语法
                fields = ", ".join(user_data.keys())
                placeholders = ", ".join(["?"] * len(user_data))
                values = list(user_data.values())
                
                # 执行插入，使用INSERT OR IGNORE忽略唯一键冲突
                try:
                    cursor.execute(
                        f"INSERT OR IGNORE INTO user_info ({fields}) VALUES ({placeholders})",
                        values
                    )
                    # 如果有新行插入（lastrowid > 0），增加计数
                    if cursor.lastrowid:
                        success_count += 1
                except Exception as e:
                    # 记录错误但继续处理下一条
                    print(f"插入用户 {user_data.get('user', '')} 失败: {e}")
            
            # 提交事务
            conn.commit()
            #Global.LOGD(f"批量插入用户数据完成: 成功 {success_count} 条，忽略 {len(user_data_list) - success_count} 条")
            return success_count
        except Exception as e:
            conn.rollback()
            Global.LOGE(f"批量插入用户数据整体失败: {e}")
            return success_count
        finally:
            # 写入连接由DbManager管理，不需要释放
            pass
    
    @staticmethod
    def import_users(filepath: str,fields:dict, status: int = STATUS_UNUSED) -> int:
        """
        从文件导入用户数据
        
        Args:
            filepath: 文件路径
            status: 导入用户状态
            
        Returns:
            int: 成功导入的用户数量
        """
        if not os.path.exists(filepath):
            return 0
            
        user_data_list = []
        try:
            with open(filepath, 'r', encoding='utf-8') as f:
                for line in f:
                    line = line.strip()
                    if not line or line[:2] == "##":
                        continue
                    
                    # 解析行数据，格式应该是通过----分隔的字段
                    field_datas = line.split('----')
                    if len(field_datas) < 2:
                        continue

                    user_data ={}
                    if fields:
                        for index, field_data in enumerate(field_datas):
                            if index > (len(fields)-1):#超出字段显示 要去掉第一个id字段
                                break
                            field_name =fields[index+1]
                            if field_name == 'flag':
                                field_data = UserManager.STATUS_UNUSED
                            user_data[field_name] = field_data

                        # 添加到批量列表
                        user_data_list.append(user_data)
            
            # 批量插入用户数据
            if user_data_list:
                return UserManager.batch_insert_users(user_data_list)
            return 0
        except Exception as e:
            print(f"导入用户数据失败: {e}")
            return 0
    
    @staticmethod
    def export_users(filepath: str, status: int) -> int:
        """
        导出特定状态的用户数据到文件
        
        Args:
            filepath: 导出文件路径
            status: 用户状态
            
        Returns:
            int: 导出的用户数量
        """
        conn = DbManager.get_conn()
        if not conn:
            return 0
            
        try:
            cursor = conn.cursor()
            cursor.execute("SELECT * FROM user_info WHERE flag = ?", (status,))
            users = cursor.fetchall()
            
            # 确保目录存在
            os.makedirs(os.path.dirname(filepath), exist_ok=True)
            
            # 写入文件
            with open(filepath, 'w', encoding='utf-8') as f:
                for user in users:
                    # 构建----分隔的字段
                    line = '----'.join([
                        str(user['user'] or ''),
                        str(user['pass'] or ''),
                        str(user['user_id'] or ''),
                        str(user['token'] or ''),
                        str(user['mail'] or ''),
                        str(user['mail_pass'] or ''),
                        str(user['card_name'] or ''),
                        str(user['source_info'] or ''),
                        str(user['upload_id'] or '')
                    ])
                    f.write(line + '\n')
            
            return len(users)
        except Exception as e:
            print(f"导出用户数据失败: {e}")
            return 0
        finally:
            DbManager.release_connection(conn)
    
    @staticmethod
    def delete_user(username: str) -> bool:
        """
        删除用户
        
        Args:
            username: 用户名
            
        Returns:
            bool: 是否删除成功
        """
        conn = DbManager.get_conn(for_writing=True)
        if not conn:
            return False
            
        try:
            cursor = conn.cursor()
            cursor.execute("DELETE FROM user_info WHERE user = ?", (username,))
            conn.commit()
            
            # 从已使用列表中移除
            if username in UserManager._used_users:
                UserManager._used_users.remove(username)
                
            return cursor.rowcount > 0
        except Exception as e:
            conn.rollback()
            print(f"删除用户失败: {e}")
            return False
        
    @staticmethod
    def get_email_account() -> Tuple[str, str]:
        """
        获取一个邮箱账号
        
        Returns:
            Tuple[str, str]: (邮箱地址, 密码)
        """
        conn = DbManager.get_conn()
        if not conn:
            return "", ""
            
        try:
            cursor = conn.cursor()
            # 查询邮箱非空的账号
            cursor.execute(
                "SELECT mail, mail_pass FROM user_info WHERE mail IS NOT NULL AND mail != '' LIMIT 1"
            )
            result = cursor.fetchone()
            if result:
                return result['mail'], result['mail_pass']
            return "", ""
        except Exception as e:
            print(f"获取邮箱账号失败: {e}")
            return "", ""
        finally:
            DbManager.release_connection(conn)
            
    @staticmethod
    def get_one_email_account() -> Tuple[str, str, int]:
        """
        从邮箱表中获取一个未使用的邮箱账号，并将其添加到黑名单中
        此方法使用专用的邮箱互斥锁，确保同一时间只有一个线程可以获取邮箱
        
        Returns:
            Tuple[str, str, int]: (邮箱地址, 密码, 邮箱ID)，如果获取失败则返回("", "", 0)
        """
        # 使用专用的邮箱互斥锁，不影响其他数据库操作
        UserManager._email_mutex.lock()
        try:
            conn = DbManager.get_conn(for_writing=True)
            if not conn:
                return "", "", 0
                
            try:
                cursor = conn.cursor()
                
                # 构建查询条件，排除已使用的邮箱
                placeholders = ','.join(['?'] * len(UserManager._used_emails)) if UserManager._used_emails else "''"
                query = f"""
                    SELECT id, mail, mail_pass FROM mail_info 
                    WHERE flag = 0 
                    AND mail NOT IN ({placeholders})
                    LIMIT 1
                """
                params = UserManager._used_emails if UserManager._used_emails else []
                
                cursor.execute(query, params)
                result = cursor.fetchone()
                
                if not result:
                    # 没有可用邮箱
                    Global.LOGD("没有可用的未使用邮箱账号")
                    return "", "", 0

                email = result[1]  # 第二个元素是mail
                email_pass = result[2]  # 第三个元素是mail_pass
                
                # 更新邮箱状态为使用中(1)
                # update_query = "UPDATE mail_info SET flag = 1, update_time = datetime('now') WHERE id = ?"
                # cursor.execute(update_query, (email_id,))
                # conn.commit()
                
                # 添加到已使用邮箱列表
                if email and email not in UserManager._used_emails:
                    UserManager._used_emails.append(email)

                
                return email, email_pass
            except Exception as e:
                conn.rollback()
                Global.LOGE(f"获取邮箱账号失败: {e}")
                return "", "", 0
            finally:
                DbManager.release_connection(conn)
        finally:
            UserManager._email_mutex.unlock()
    
    @staticmethod
    def release_email_from_blacklist(email: str) -> bool:
        """
        从黑名单中释放邮箱，允许其他线程使用
        
        Args:
            email: 要释放的邮箱地址
            
        Returns:
            bool: 是否成功释放
        """
        if not email:
            return False
            
        UserManager._email_mutex.lock()
        try:
            # 从已使用列表中移除
            if email in UserManager._used_emails:
                UserManager._used_emails.remove(email)
                return True
            return False
        finally:
            UserManager._email_mutex.unlock()
    
    @staticmethod
    def reset_email_status(email: str) -> bool:
        """
        重置邮箱状态为未使用，并从黑名单中移除
        
        Args:
            email: 要重置的邮箱地址
            
        Returns:
            bool: 是否成功重置
        """
        if not email:
            return False
            
        UserManager._email_mutex.lock()
        try:
            conn = DbManager.get_conn(for_writing=True)
            if not conn:
                return False
                
            try:
                cursor = conn.cursor()
                
                # 更新邮箱状态为未使用(0)
                update_query = "UPDATE mail_info SET flag = 0, update_time = datetime('now') WHERE mail = ?"
                cursor.execute(update_query, (email,))
                conn.commit()
                
                # 从已使用列表中移除
                if email in UserManager._used_emails:
                    UserManager._used_emails.remove(email)

                
                return cursor.rowcount > 0
            except Exception as e:
                conn.rollback()
                Global.LOGE(f"重置邮箱状态失败: {e}")
                return False
            finally:
                DbManager.release_connection(conn)
        finally:
            UserManager._email_mutex.unlock()
    
    @staticmethod
    def update_email_status(email: str,status=0) -> bool:
        """
        设置邮箱状态为使用成功(2)
        
        Args:
            email: 要更新的邮箱地址
            
        Returns:
            bool: 是否成功更新
        """
        if not email:
            return False
            
        UserManager._email_mutex.lock()
        try:
            conn = DbManager.get_conn(for_writing=True)
            if not conn:
                return False
                
            try:
                cursor = conn.cursor()
                
                # 更新邮箱状态为使用成功(2)
                update_query = "UPDATE mail_info SET flag = ?, update_time = datetime('now') WHERE mail = ?"
                cursor.execute(update_query, (status,email,))
                conn.commit()
                if email in UserManager._used_emails : #只要更新状态就应该清除黑名单
                    UserManager._used_emails.remove(email)
                return cursor.rowcount > 0
            except Exception as e:
                conn.rollback()
                Global.LOGE(f"设置邮箱状态为成功失败: {e}")
                return False
            finally:
                DbManager.release_connection(conn)
        finally:
            UserManager._email_mutex.unlock()
    
    @staticmethod
    def close():
        """关闭用户管理模块，释放资源"""
        UserManager._data_mutex.lock()
        try:
            UserManager._used_users.clear()
            UserManager._used_emails.clear()
            UserManager._is_initialized = False
            DbManager.close()
        finally:
            UserManager._data_mutex.unlock()
    
    @staticmethod
    def update_user_by_name(username: str, user_data: Dict) -> bool:
        """
        基于用户名更新用户数据
        
        Args:
            username: 用户名
            user_data: 要更新的用户数据字典
            
        Returns:
            bool: 更新是否成功
        """
        if not username or not user_data:
            print("更新用户数据失败：用户名为空或没有提供更新数据")
            return False
            
        UserManager._data_mutex.lock()
        try:
            # 先查询用户ID
            conn = DbManager.get_conn()
            if not conn:
                return False
                
            try:
                cursor = conn.cursor()
                cursor.execute("SELECT id FROM user_info WHERE user = ?", (username,))
                result = cursor.fetchone()
                if not result:
                    print(f"更新用户数据失败：未找到用户 {username}")
                    return False
                    
                user_id = result['id']
                
                # 检查是否更新了状态字段，且状态为成功、失败或上传
                if 'flag' in user_data and user_data['flag'] in (UserManager.STATUS_SUCCESS, UserManager.STATUS_FAILED, UserManager.STATUS_UPLOAD):
                    # 从已使用列表中移除
                    if username in UserManager._used_users:
                        UserManager._used_users.remove(username)

                
                # 使用DbManager更新数据
                return DbManager.update_user_info(user_id, user_data)
            except Exception as e:
                print(f"更新用户数据失败: {e}")
                return False
            finally:
                DbManager.release_connection(conn)
        finally:
            UserManager._data_mutex.unlock()
    
    @staticmethod
    def delete_users_by_condition(status: int = None, conditions: Dict[str, Any] = None) -> int:
        """
        根据条件批量删除用户
        
        Args:
            status: 用户状态，None表示不按状态筛选
            conditions: 自定义查询条件，字典格式{字段名:值}
            
        Returns:
            int: 删除的记录数量
        """
        conn = DbManager.get_conn(for_writing=True)
        if not conn:
            return 0
        
        try:
            cursor = conn.cursor()
            
            # 构建查询SQL
            query = "DELETE FROM user_info"
            params = []
            
            # 构建查询条件
            where_clauses = []
            
            # 添加状态过滤条件
            if status is not None:
                where_clauses.append("flag = ?")
                params.append(status)
            
            # 添加自定义查询条件
            if conditions:
                for field, value in conditions.items():
                    if value is not None:
                        if isinstance(value, str) and '%' in value:
                            # 如果包含%，则使用LIKE查询
                            where_clauses.append(f"{field} LIKE ?")
                        else:
                            where_clauses.append(f"{field} = ?")
                        params.append(value)
            
            # 合并所有查询条件
            if where_clauses:
                query += " WHERE " + " AND ".join(where_clauses)
            else:
                # 如果没有条件，为安全起见，不执行删除
                return 0
            
            # 执行删除
            cursor.execute(query, params)
            conn.commit()
            
            # 清理已使用列表中的相关用户
            if status is not None or conditions:
                UserManager._used_users.clear()  # 简单处理：清空所有缓存
            
            return cursor.rowcount
        except Exception as e:
            conn.rollback()
            print(f"批量删除用户失败: {e}")
            return 0
    
    @staticmethod
    def delete_mail_by_condition(status: int = None, conditions: Dict[str, Any] = None, delete_all: bool = False) -> int:
        """
        根据条件批量删除邮箱账号
        
        Args:
            status: 邮箱状态，None表示不按状态筛选
            conditions: 自定义查询条件，字典格式{字段名:值}
            delete_all: 是否删除所有记录，True时会忽略条件限制并删除全部记录
            
        Returns:
            int: 删除的记录数量
        """
        conn = DbManager.get_conn(for_writing=True)
        if not conn:
            return 0
        
        try:
            cursor = conn.cursor()
            
            if delete_all:
                # 如果指定了删除所有记录，直接执行
                query = "DELETE FROM mail_info"
                cursor.execute(query)
                conn.commit()
                return cursor.rowcount
            
            # 构建查询SQL
            query = "DELETE FROM mail_info"
            params = []
            
            # 构建查询条件
            where_clauses = []
            
            # 添加状态过滤条件
            if status is not None:
                where_clauses.append("flag = ?")
                params.append(status)
            
            # 添加自定义查询条件
            if conditions:
                for field, value in conditions.items():
                    if value is not None:
                        if isinstance(value, str) and '%' in value:
                            # 如果包含%，则使用LIKE查询
                            where_clauses.append(f"{field} LIKE ?")
                        else:
                            where_clauses.append(f"{field} = ?")
                        params.append(value)
            
            # 合并所有查询条件
            if where_clauses:
                query += " WHERE " + " AND ".join(where_clauses)
            else:
                # 如果没有条件，为安全起见，不执行删除
                return 0
            
            # 执行删除
            cursor.execute(query, params)
            conn.commit()
            
            return cursor.rowcount
        except Exception as e:
            conn.rollback()
            print(f"批量删除邮箱账号失败: {e}")
            return 0

    @staticmethod
    def delete_mail_by_names(emails: List[str]) -> int:
        """
        根据邮箱名称列表批量删除邮箱账号
        
        Args:
            emails: 要删除的邮箱名称列表
            
        Returns:
            int: 删除的记录数量
        """
        if not emails:
            return 0
        
        conn = DbManager.get_conn(for_writing=True)
        if not conn:
            return 0
        
        try:
            cursor = conn.cursor()
            
            # 构建IN子句的参数
            placeholders = ','.join(['?'] * len(emails))
            
            # 执行批量删除
            query = f"DELETE FROM mail_info WHERE mail IN ({placeholders})"
            cursor.execute(query, emails)
            conn.commit()
            
            # 从已使用列表中移除这些邮箱
            for email in emails:
                if email in UserManager._used_emails:
                    UserManager._used_emails.remove(email)
            
            return cursor.rowcount
        except Exception as e:
            conn.rollback()
            print(f"批量删除邮箱账号失败: {e}")
            return 0

    @staticmethod
    def get_mail_accounts(count: int = -1, offset: int = 0, conditions: Dict[str, Any] = None, fields: List[str] = None, format: str = 'dict') -> List[Any]:
        """
        获取邮箱账号列表
        
        Args:
            count: 获取数量，-1表示不限制数量
            offset: 偏移量
            conditions: 自定义查询条件，字典格式{字段名:值}
            fields: 自定义查询字段列表，默认查询所有字段
            format: 返回数据格式，'dict'返回字典列表，'list'返回二维列表
            
        Returns:
            List[Dict]或List[List]: 邮箱账号数据列表
        """
        conn = DbManager.get_conn()
        if not conn:
            return []
        
        try:
            cursor = conn.cursor()
            
            # 构建查询字段
            default_fields = ["id", "mail", "mail_pass", "flag", "create_time", "update_time"]
            
            # 如果指定了查询字段，使用指定字段，否则使用默认字段
            select_fields = fields if fields else default_fields
            
            # 确保字段列表不为空
            if not select_fields:
                select_fields = default_fields

            # 处理update_time字段，转换为北京时间
            processed_select_fields = []
            for field in select_fields:
                if field == 'update_time':
                    processed_select_fields.append("datetime(update_time, '+8 hours') AS update_time")
                else:
                    processed_select_fields.append(field)

            # 构建查询SQL
            query = f"SELECT {', '.join(processed_select_fields)} FROM mail_info"
            params = []
            
            # 构建查询条件
            where_clauses = []
            
            # 添加自定义查询条件
            if conditions:
                for field, value in conditions.items():
                    if value is not None:
                        if isinstance(value, str) and '%' in value:
                            # 如果包含%，则使用LIKE查询
                            where_clauses.append(f"{field} LIKE ?")
                        else:
                            where_clauses.append(f"{field} = ?")
                        params.append(value)
            
            # 合并所有查询条件
            if where_clauses:
                query += " WHERE " + " AND ".join(where_clauses)
            
            # 添加排序
            query += " ORDER BY id"
            
            # 添加分页
            if count > 0:
                query += " LIMIT ?"
                params.append(count)
            
                if offset > 0:
                    query += " OFFSET ?"
                    params.append(offset)
            
            cursor.execute(query, params)
            rows = cursor.fetchall()
            
            if format == 'dict':
                # 返回字典列表
                return [dict(row) for row in rows]
            elif format == 'list':
                # 返回二维列表，第一列为累加序号
                # 状态文本映射
                status_text = {
                    0: '未使用',
                    1: '使用中',
                    2: '已使用'
                }
                
                result = []
                for i, row in enumerate(rows):
                    row_dict = dict(row)
                    row_data = [
                        str(i + 1),  # 序号
                        row_dict.get('mail', ''),  # 邮箱
                        row_dict.get('mail_pass', ''),  # 邮箱密码
                        status_text.get(row_dict.get('flag'), '')  # 状态
                    ]
                    result.append(row_data)
                
                return result
            else:
                # 不支持的格式，返回空列表
                return []
        except Exception as e:
            Global.LOGE(f"查询邮箱账号数据失败: {e}")
            return []
        finally:
            DbManager.release_connection(conn)

    @staticmethod
    def import_mail(filepath: str,fields:dict, status: int = 0) -> int:
        """
        从文件导入邮箱数据到mail_info表
        
        Args:
            filepath: 文件路径
            status: 导入邮箱状态，默认为0(未使用)
            
        Returns:
            int: 成功导入的邮箱数量
        """
        if not os.path.exists(filepath):
            return 0
        
        mail_data_list = []
        try:
            with open(filepath, 'r', encoding='utf-8') as f:
                for line in f:
                    line = line.strip()
                    if not line or line[:2]=="##":
                        continue
                    
                    # 解析行数据，格式应该是通过----分隔的字段
                    field_datas = line.split('----')
                    if len(field_datas) < 1:
                        continue

                    mail_data = {}
                    if fields:
                        for index, field_data in enumerate(field_datas):
                            if index > (len(fields) - 1):  # 超出字段显示 要去掉第一个id字段
                                break
                            field_name = fields[index + 1]
                            if field_name == 'flag':
                                field_data = UserManager.STATUS_UNUSED
                            mail_data[field_name] = field_data
                        # 添加到批量列表
                        mail_data_list.append(mail_data)
        
            # 批量插入邮箱数据
            if mail_data_list:
                return UserManager.batch_insert_mail(mail_data_list)
            return 0
        except Exception as e:
            print(f"导入邮箱数据失败: {e}")
            return 0

    @staticmethod
    def batch_insert_mail(mail_data_list: List[Dict]) -> int:
        """
        批量插入邮箱数据
        
        Args:
            mail_data_list: 邮箱数据字典列表
            
        Returns:
            int: 成功插入的记录数
        """
        if not mail_data_list:
            return 0
        
        success_count = 0
        conn = DbManager.get_conn(for_writing=True)
        if not conn:
            return 0
        
        try:
            cursor = conn.cursor()
            
            # 开始事务
            conn.execute("BEGIN TRANSACTION")
            
            for mail_data in mail_data_list:
                if not mail_data or 'mail' not in mail_data:
                    continue
                    
                # 确保有flag字段
                if 'flag' not in mail_data:
                    mail_data['flag'] = 0
                
                # 准备SQL语句，使用INSERT OR IGNORE语法
                fields = ", ".join(mail_data.keys())
                placeholders = ", ".join(["?"] * len(mail_data))
                values = list(mail_data.values())
                
                # 执行插入，使用INSERT OR IGNORE忽略唯一键冲突
                try:
                    cursor.execute(
                        f"INSERT OR IGNORE INTO mail_info ({fields}) VALUES ({placeholders})",
                        values
                    )
                    # 如果有新行插入（lastrowid > 0），增加计数
                    if cursor.lastrowid:
                        success_count += 1
                except Exception as e:
                    # 记录错误但继续处理下一条
                    print(f"插入邮箱 {mail_data.get('mail', '')} 失败: {e}")
            
            # 提交事务
            conn.commit()
            Global.LOGD(f"批量插入邮箱数据完成: 成功 {success_count} 条，忽略 {len(mail_data_list) - success_count} 条")
            return success_count
        except Exception as e:
            conn.rollback()
            Global.LOGE(f"批量插入邮箱数据整体失败: {e}")
            return success_count
        finally:
            # 写入连接由DbManager管理，不需要释放
            pass


# 使用示例
if __name__ == "__main__":
    # 初始化用户管理模块
    if UserManager.initialize():
        print("用户管理模块初始化成功")
        
        # 导入待用账号
        imported = UserManager.import_users("账号管理/待用/待用账号.txt", UserManager.STATUS_UNUSED)
        print(f"导入了 {imported} 个待用账号")
        
        # 获取两个账号进行测试
        users = UserManager.get_user_info(2)
        for user in users:
            print(f"获取到用户: {user['user']}")
            
            # 模拟使用后更新状态为成功
            UserManager.update_user_status(user['user'], UserManager.STATUS_SUCCESS)
        
        # 使用update_user_by_name函数更新用户数据
        if users:
            test_user = users[0]['user']
            # 更新用户数据
            update_data = {
                'card_name': '测试卡片',
                'source_info': '测试资源',
                'upload_id': '12345'
            }
            if UserManager.update_user_by_name(test_user, update_data):
                print(f"成功更新用户 {test_user} 的数据")
                
                # 验证更新结果
                updated_user = UserManager.get_users(conditions={'user': test_user})
                if updated_user:
                    print(f"更新后的用户数据: {updated_user[0]}")
            else:
                print(f"更新用户 {test_user} 数据失败")
        
        # 获取所有账号数量
        total_users = UserManager.count_users()
        print(f"当前共有 {total_users} 个账号")
        
        # 使用自定义条件统计
        gmail_count = UserManager.count_users(conditions={"mail": "%gmail.com"})
        print(f"Gmail邮箱的账号数量: {gmail_count}")
        
        # 组合条件统计
        success_gmail_count = UserManager.count_users(
            status=UserManager.STATUS_SUCCESS,
            conditions={"mail": "%gmail.com"}
        )
        print(f"成功状态的Gmail邮箱账号数量: {success_gmail_count}")
        
        # 获取所有账号（不限制数量）
        all_users = UserManager.get_users()
        print(f"获取到所有 {len(all_users)} 个账号")
        
        # 使用自定义条件查询
        condition_users = UserManager.get_users(conditions={"mail": "%gmail.com"})
        print(f"获取到Gmail邮箱的账号: {len(condition_users)} 个")
        
        # 组合条件查询 - 查询成功状态且有特定邮箱的账号
        gmail_success_users = UserManager.get_users(
            status=UserManager.STATUS_SUCCESS,
            conditions={"mail": "%gmail.com"}
        )
        print(f"获取到成功状态的Gmail邮箱账号: {len(gmail_success_users)} 个")
        
        # 使用自定义查询字段 - 只查询用户名和邮箱
        custom_fields_users = UserManager.get_users(
            fields=["user", "mail", "flag"]
        )
        print(f"获取用户名和邮箱数据示例: {custom_fields_users[:2]}")
        
        # 组合使用自定义字段和条件
        custom_query = UserManager.get_users(
            status=UserManager.STATUS_SUCCESS,
            fields=["id", "user", "mail", "card_name"],
            conditions={"mail": "%gmail.com"}
        )
        print(f"自定义查询示例: {custom_query[:2]}")
        
        # 分页获取成功账号（每页10个）
        page = 0
        page_size = 10
        while True:
            success_users = UserManager.get_users(
                UserManager.STATUS_SUCCESS, 
                count=page_size, 
                offset=page * page_size
            )
            if not success_users:
                break
                
            print(f"第 {page+1} 页成功账号: {len(success_users)} 个")
            page += 1
            
        # 导出成功账号
        exported = UserManager.export_users("账号管理/成功/成功账号.txt", UserManager.STATUS_SUCCESS)
        print(f"导出了 {exported} 个成功账号")
        
        # 关闭模块
        UserManager.close()
    else:
        print("用户管理模块初始化失败")